<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>WebSocket Chat</title>
    <script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
</head>
<body>
<script type="text/javascript">

    var from = "";
    var to = "";
    $(function(){
        from = prompt("请输入您的姓名","");
        while(from=='' || from==undefined || from==null){
            from = prompt("请输入您的姓名","");
        }
        to = prompt("您在要跟谁聊天","");
        while(to=='' || to==undefined || to==null){
            to = prompt("您在要跟谁聊天","");
        }
        var message = "上线";
        var type = "ONLINE";
        send(message,type);   //发送上线
        $("#sendMessage").focus();  //输入框聚焦
    });
    var socket;
    if (!window.WebSocket) {
        window.WebSocket = window.MozWebSocket;
    }
    if (window.WebSocket) {
        socket = new WebSocket("ws://localhost:8080/ws");
        socket.onmessage = function(event) {
            var message = JSON.parse(event.data);
            var ta = document.getElementById('responseText');
            ta.value = ta.value + '\n' + message.from + '回复:\n'+message.content;
        };
        socket.onopen = function(event) {
            $("#tip").html(from+" 在线");
        };
        socket.onclose = function(event) {
            $("#tip").html(from+" 离线");
        };
    } else {
        alert("你的浏览器不支持 WebSocket！");
    }

    function send(message,type) {
        if(type == "COMMON"){
            var ta = document.getElementById('responseText');
            ta.value = ta.value + '\n你说:\n'+message;
        }
        message = JSON.stringify({"from":from,"to":to,"content":message,"type":type});
        if (!window.WebSocket) {
            return;
        }
        if (socket.readyState == WebSocket.OPEN) {
            socket.send(message);
        } else {
            alert("连接没有开启.");
        }
    }
</script>
<form onsubmit="return false;">
    <h3 id="tip"></h3>
    <textarea id="responseText" style="width: 500px; height: 300px;"></textarea>
    <br>
    <input id="sendMessage" type="text" name="message"  style="width: 250px" onkeypress="if(event.keyCode==13) {$('#sendButton').click();return false;}">
    <input id="sendButton" type="button" value="发送消息" onclick="send(this.form.message.value,'COMMON');$('#sendMessage').val('')">
    <input type="button" onclick="javascript:document.getElementById('responseText').value=''" value="清空聊天记录">
</form>
<br>
<br>
</body>
</html>